package com.wframe.project.jnd.util;

import java.io.IOException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;

import com.frame.database.JdataBean;
import com.frame.database.PageResult;
import com.frame.util.EncryptUtil;
import com.wframe.project.former.entity.ProductPriceAttrVo;

/**
 * 
 * 功能:WebUtils<br>
 * 参数:<br>
 * 作者:王海锋<br>
 * 时间:2017-1-13上午11:04:46<br>
 */
public class WebUtils {

	public static final long basecodetime=1483200000000l;
	
	public static Logger log=Logger.getLogger(WebUtils.class);
	
	/*
	 * web加密字符串
	 */
	private static final String decryptKey="IdPwdKey@2017";
	
   
	public static List<ProductPriceAttrVo> strToPriceAttrVo(String attrcodestr){
		List<ProductPriceAttrVo> list=new ArrayList<ProductPriceAttrVo>();
		if(StringUtils.isNotBlank(attrcodestr) && !"0".equals(attrcodestr)){
			String[] ss=attrcodestr.split("\\|");
			for(String s:ss){
				String[] attrs=s.split(":");
				ProductPriceAttrVo vo=new ProductPriceAttrVo();
				vo.setAttrid(attrs[0]);
				vo.setItemcodes(attrs[1].split(","));
				list.add(vo);
			}
		}
		return list;
	}
	
	public static void responseWrite(HttpServletResponse response,String content){
		response.setContentType("text/html;charset=utf-8");
		try {
			response.getWriter().write(content);
		} catch (IOException e) {
			Logger.getLogger(WebUtils.class).error("",e);
		}
	}
	
	public static JdataBean requestMapToBean(Map<String,String[]> requestmap){
		JdataBean bean=new JdataBean();
		String[] keys=requestmap.keySet().toArray(new String[]{});
		for(String key:keys){
			String[] vals=requestmap.get(key);
			if(vals!=null)bean.put(key, vals[0]);
		}
		return bean;
	}
	
	public static ModelAndView errorModel(Exception e){
		ModelAndView modelAndView=new ModelAndView("/website/message.jsp");
		modelAndView.addObject("error",e.getMessage());
		return modelAndView;
	}
	
	public static List<PageBean> toPageBean(PageResult pr,int len){
		List<PageBean> list=new ArrayList<PageBean>();
		int pagecount=pr.getPageCount();
		int pageno=pr.getPageNo();
		list.add(new PageBean((pageno>1?(pageno-1):1),1));
		if(pagecount<=len){
			for(int i=1;i<=pagecount;i++){
				if(i!=pageno)list.add(new PageBean(i));
				else list.add(new PageBean(i,true));
			}
		}else{
			int num=0;
			if(pageno>4){
				list.add(new PageBean(1));
				list.add(new PageBean(0,3));
				for(int i=(pageno-2);i<pageno;i++)
					list.add(new PageBean(i));
				list.add(new PageBean(pageno,true));
				for(int i=(pageno+1);i<=(pageno+2);i++){
					if(i<=pagecount)list.add(new PageBean(i));
				}
				if(pagecount>(pageno+3))list.add(new PageBean(0,3));
				if(pagecount>(pageno+2))list.add(new PageBean(pagecount));
			}else{
				for(int i=1;i<pageno;i++){
					list.add(new PageBean(i));
					num++;
				}
				list.add(new PageBean(pageno,true));
				num++;
				for(int i=1;i<(len-num);i++)
					list.add(new PageBean(num+i));
				list.add(new PageBean(0,3));
				list.add(new PageBean(pagecount));
			}
		}
		list.add(new PageBean((pageno==pagecount?pagecount:(pageno+1)),2));
		return list;
	}
	public static String toPageHtml(PageResult pr,int len){
		List<PageBean> pagelist=toPageBean(pr,len);
		String html="<div class='Pagination'><table align='center' style='margin:0 auto'><tr><td>"
				+"<div class='clearfix'>";
		for(PageBean bean:pagelist){
			if(bean.getType()==1)
				html+="<a href='javascript:gopage("+bean.getPageno()+");' class='page-btn'>上一页</a>";
			else if(bean.getType()==2)html+="<a href='javascript:gopage("+bean.getPageno()+");' class='page-btn'>下一页</a>";
			else if(bean.getType()==3)html+="<a href='javascript:;'>...</a>";
			else html+="<a href='javascript:gopage("+bean.getPageno()+");' class='"+(bean.isCur()?"cur":"")+"'>"+bean.getPageno()+"</a>";
		}
		html+="</div>";
		html+="</td><td><div class='clearfix'>"
			+"<span>共"+pr.getPageCount()+"页，到第</span>"
			+"<span class='pag-inp'><input name='topagenum' onkeyup='inputNumber(this)' type='text' value=''></span>"
			+"<span>页</span>"
			+" <span class='pag-go'><button onclick='topageclick()'>确定</button></span>"
			+"</div></td></tr></table>";
		html+="</div>";
		return html;
	}

	/**
	 * 
	 * 功能:Aes加密<br>
	 * 参数:<br>
	 * 作者:王海锋<br>
	 * 时间:2017-1-13上午11:04:06<br>
	 */
	public static String aesEncode(String content){
		if(content==null || content.length()<1)return null;
		try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			Cipher cipher = Cipher.getInstance("AES");
			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(decryptKey.getBytes());
			kgen.init(128,secureRandom);
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
			byte[] byteContent = content.getBytes("utf-8");
			cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
			byte[] byteRresult = cipher.doFinal(byteContent);
			return new String(Hex.encodeHex(byteRresult));
		} catch (Exception e) {
			log.error("",e);
		}
		return null;
	}
	/**
	 * 
	 * 功能:Aes解密<br>
	 * 参数:<br>
	 * 作者:王海锋<br>
	 * 时间:2017-1-13上午11:04:06<br>
	 */
	public static String aesDecrypt(String value) throws Exception{
		KeyGenerator kgen = KeyGenerator.getInstance("AES");
		Cipher cipher = Cipher.getInstance("AES");
		if (value==null || value.length() < 1)
			return null;
		try {
			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" );   
	        secureRandom.setSeed(decryptKey.getBytes());  
			byte[] byteRresult = Hex.decodeHex(value.toCharArray());
			kgen.init(128, secureRandom);
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
			cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
			byte[] result = cipher.doFinal(byteRresult);
			return new String(result);
		}catch (Exception e) {
			log.error("",e);
		}
		return null;
	}
	/**
	 * 
	 * 功能:Des加密<br>
	 * 参数:<br>
	 * 作者:王海锋<br>
	 * 时间:2017-1-13上午11:04:06<br>
	 */
	public static String desEncode(String s) throws Exception{
		return EncryptUtil.desEncode(s, decryptKey);
	}
	/**
	 * 
	 * 功能:Des解密<br>
	 * 参数:<br>
	 * 作者:王海锋<br>
	 * 时间:2017-1-13上午11:04:06<br>
	 */
	public static String desDecrypt(String s) throws Exception{
		return EncryptUtil.desDecrypt(s, decryptKey);
	}
}
